#include <stdlib.h>
#include <getopt.h>
#include <libgen.h>
#include <sys/epoll.h>
#include "server_init.h" 
#include "socket_rlimit.h" 
#include "database.h"
#include "log.h"

#define MAX_EVENTS 512
#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))

static inline void print_usage(char *progname);

int main(int argc, char **argv)
{  
	int 			listenfd, connfd;
	int 			serv_port = 0;
	int 			daemon_run = 0;
	char 		   *progname = NULL;
	int 			opt;
	int 			rv;
	int 			i, j;
	int 			found;
	char 			buf[1024];
	char 			buf1[1024];
	int 			epollfd;
	struct 			epoll_event event;
	struct 			epoll_event event_array[MAX_EVENTS];
	int 			events;
	struct 			sockaddr_in	  cliaddr;
	socklen_t		len = sizeof(struct sockaddr);
	char			str[] = "/";
	char		   *username = NULL;
	struct 			option long_options[] =
	{ 
		{"daemon", no_argument, NULL, 'b'},
		{"port", required_argument, NULL, 'p'},
		{"help", no_argument, NULL, 'h'},
		{NULL, 0, NULL, 0}
	};

	progname = basename(argv[0]);

	/* Parser the command line parameters */
	while ((opt = getopt_long(argc, argv, "bp:h", long_options, NULL)) != -1)
	{ 
		switch (opt)
		{ 
			case 'b':
				daemon_run=1;
				break;
			case 'p':
				serv_port = atoi(optarg);
				break;
			case 'h': /* Get help information */
				print_usage(progname);
				return EXIT_SUCCESS;
			default:
				break;
		} 
	} 
	if( !serv_port )
	{ 
		print_usage(progname);
		return -1;
	}

	set_socket_rlimit(); /* set max open socket count */

	if( (listenfd=socket_server_init(NULL, serv_port)) < 0 )
	{
		PARSE_LOG_ERROR("ERROR: %s server listen on port %d failure\n", argv[0],serv_port);
		return -2;
	}
	PARSE_LOG_INFO("%s server start to listen on port %d\n", argv[0],serv_port);
	
	/* set program running on background */
	if( daemon_run )
	{
		daemon(0, 0);
	}
	
	if( (epollfd=epoll_create(MAX_EVENTS)) < 0 )
	{
		PARSE_LOG_ERROR("epoll_create() failure: %s\n", strerror(errno));
		return -3;
	}
	
	//event.events = EPOLLIN|EPOLLET;
	event.events = EPOLLIN;
	event.data.fd = listenfd;
	
	if( epoll_ctl(epollfd, EPOLL_CTL_ADD, listenfd, &event) < 0)
	{
		PARSE_LOG_ERROR("epoll add listen socket failure: %s\n", strerror(errno));
		return -4;
	}
	
	for ( ; ; )
	{
		/* program will blocked here */
		events = epoll_wait(epollfd, event_array, MAX_EVENTS, -1);
		if(events < 0)
		{
			PARSE_LOG_ERROR("epoll failure: %s\n", strerror(errno));
			break;
		}
		else if(events == 0)
		{
			PARSE_LOG_ERROR("epoll get timeout\n");
			continue;
		}
		
		/* rv>0 is the active events count */
		for(i=0; i<events; i++)
		{
			if ( (event_array[i].events&EPOLLERR) || (event_array[i].events&EPOLLHUP) )
			{
				PARSE_LOG_ERROR("epoll_wait get error on fd[%d]: %s\n", event_array[i].data.fd, strerror(errno));
				epoll_ctl(epollfd, EPOLL_CTL_DEL, event_array[i].data.fd, NULL);
				close(event_array[i].data.fd);
			}
			
			/* listen socket get event means new client start connect now */
			if( event_array[i].data.fd == listenfd )
			{
				if( (connfd=accept(listenfd, (struct sockaddr *)&cliaddr, &len)) < 0)
				{
					PARSE_LOG_ERROR("accept new client failure: %s\n", strerror(errno));
					continue;
				}
				
				event.data.fd = connfd;
				//event.events = EPOLLIN|EPOLLET;
				event.events = EPOLLIN;
				if( epoll_ctl(epollfd, EPOLL_CTL_ADD, connfd, &event) < 0 )
				{
					PARSE_LOG_ERROR("epoll add client socket failure: %s\n", strerror(errno));
					close(event_array[i].data.fd);
					continue;
				}
				PARSE_LOG_DEBUG("epoll add new client[%s:%d] socket[%d] ok !\n", inet_ntoa(cliaddr.sin_addr), ntohs(cliaddr.sin_port), connfd);
			}
			else /* already connected client socket get data incoming */
			{
				memset(buf, 0, sizeof(buf));
				if( (rv=read(event_array[i].data.fd, buf, sizeof(buf))) <= 0)
				{
					PARSE_LOG_DEBUG("socket[%d] read failure or get disconncet and will be removed.\n",
							event_array[i].data.fd);
					epoll_ctl(epollfd, EPOLL_CTL_DEL, event_array[i].data.fd, NULL);
					close(event_array[i].data.fd);
					continue;
				}
				else
				{
					PARSE_LOG_DEBUG("socket[%d] read %d bytes data: %s\n", event_array[i].data.fd, rv, buf);

					strcpy(buf1,buf);
					username = strtok(buf, str);
					PARSE_LOG_DEBUG("buf1: %s\n", buf1);
					PARSE_LOG_DEBUG("username: %s\n", username);

					database(buf1, username);
				}
			}
		} /* for(i=0; i<rv; i++) */
	} /* while(1) */

CleanUp:
	close(listenfd);
	return 0;
}

static inline void print_usage(char *progname)
{
	printf("Usage: %s [OPTION]...\n", progname);

	printf(" %s is a socket server program, which used to verify client and echo back string from it\n",
			progname);
	printf("\nMandatory arguments to long options are mandatory for short options too:\n");

	printf(" -b[daemon ] set program running on background\n");
	printf(" -p[port ] Socket server port address\n");
	printf(" -h[help ] Display this help information\n");

	printf("\nExample: %s -b -p 8900\n", progname);
	return ;
}
